package com.example.blogsystemssm.controller;

import com.example.blogsystemssm.common.AjaxResult;
import com.example.blogsystemssm.common.Constant;
import com.example.blogsystemssm.common.SessionUtil;
import com.example.blogsystemssm.model.ArticleInfo;
import com.example.blogsystemssm.model.UserInfo;
import com.example.blogsystemssm.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/list")
    public List<ArticleInfo> getList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USERINFO_KEY);
            return articleService.getList(userInfo.getId());
        }
        return null;
    }

    @RequestMapping("/del")
    public int delArt(HttpServletRequest request, String aid) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.SESSION_USERINFO_KEY) != null) {
            UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USERINFO_KEY);
            Integer uid = userInfo.getId();
            Integer ad = Integer.parseInt(aid);
            return articleService.delArt(ad, uid);
        }
        return -1;
    }

    @RequestMapping("/detail")
    public Object getDetail(Integer aid) {
        if (aid != null && aid > 0) {
            return AjaxResult.success("获取文章详情成功 :)", articleService.getDetail(aid));
//            return articleService.getDetail(aid);
        }
        return AjaxResult.fail(-1, "获取文章详情失败 :(");
    }

    @RequestMapping("/details")
    public Object getDetails(Integer aid, HttpServletRequest request) {
        if (aid != null && aid > 0) {
            ArticleInfo articleInfo = articleService.getDetail(aid);
            UserInfo userInfo = SessionUtil.getLoginUSer(request);
            return AjaxResult.success(articleInfo);
        }
        return AjaxResult.fail(-1, "查询失败");
    }

    @RequestMapping("/update")
    public Object updateContent() {
        return " ";
    }

    @RequestMapping("/count")
    public Object getCount() {
        Integer count = articleService.getCount(1);
        if (count != null && count >= 0) {
            System.out.println("获取到count：" + count);
            return AjaxResult.success(count);
        }
        return AjaxResult.fail(-1, "获取文章数失败");
    }
}
